package com.tttshaoqi.server.service.impl;

import com.tttshaoqi.common.result.Result;
import com.tttshaoqi.server.mapper.*;
import com.tttshaoqi.pojo.entity.*;
import com.tttshaoqi.server.service.PostService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
@RequiredArgsConstructor
public class PostServiceImpl implements PostService {
    private final PostMapper postMapper;
    private final ImageMapper imageMapper;
    private final TagMapper tagMapper;
    private final PostTagMapper postTagMapper;

    @Transactional
    @Override
    public Post create(Long userId, String title, String content, List<String> imageUrls, List<String> tags) {
        Post post = new Post()
                .setUserId(userId)
                .setTitle(title)
                .setContent(content)
                .setLikeCount(0L)
                .setCommentCount(0L)
                .setCreatedAt(LocalDateTime.now())
                .setUpdatedAt(LocalDateTime.now());
        postMapper.insert(post);
        saveImages(post.getId(), imageUrls);
        saveTags(post.getId(), tags);
        return post;
    }

    @Transactional
    @Override
    public Optional<Post> update(Long userId, Long postId, String title, String content, List<String> imageUrls, List<String> tags) {
        Post post = postMapper.findById(postId);
        if (post == null) return Optional.empty();
        if (!post.getUserId().equals(userId)) return Optional.empty();
        post.setTitle(title).setContent(content).setUpdatedAt(LocalDateTime.now());
        postMapper.update(post);
        imageMapper.deleteByPostId(postId);
        postTagMapper.deleteByPostId(postId);
        saveImages(postId, imageUrls);
        saveTags(postId, tags);
        return Optional.of(post);
    }

    @Transactional
    @Override
    public boolean delete(Long userId, Long postId) {
        Post post = postMapper.findById(postId);
        if (post == null) return false;
        if (!post.getUserId().equals(userId)) return false;
        imageMapper.deleteByPostId(postId);
        postTagMapper.deleteByPostId(postId);
        postMapper.delete(postId);
        return true;
    }

    @Override
    @Transactional
    public Result<Void> banchDelete(Long id, List<Long> ids) {
        List<Post> posts = postMapper.listByUserIdAndPostIds(id,ids);
        try{
            for(Post post : posts){
                imageMapper.deleteByPostId(post.getId());
                postTagMapper.deleteByPostId(post.getId());
                postMapper.delete(post.getId());
            }
            return Result.success();
        }catch (Exception e){
            e.printStackTrace();
        }
        return Result.error("删除失败，请稍后再试");
    }

    private void saveImages(Long postId, List<String> imageUrls){
        if (imageUrls == null || imageUrls.isEmpty()) return;
        List<Image> list = new ArrayList<>();
        int i = 0;
        for (String url : imageUrls){
            list.add(new Image().setPostId(postId).setUrl(url).setSortOrder(i++).setCreatedAt(LocalDateTime.now()));
        }
        imageMapper.batchInsert(list);
    }

    private void saveTags(Long postId, List<String> tags){
        if (tags == null || tags.isEmpty()) return;
        for (String tagName : tags){
            Tag exist = tagMapper.findByName(tagName);
            if (exist == null){
                Tag t = new Tag();
                t.setName(tagName);
                tagMapper.insert(t);
                exist = t;
            }
            PostTag pt = new PostTag();
            pt.setPostId(postId);
            pt.setTagId(exist.getId());
            postTagMapper.insert(pt);
        }
    }
}



